package com.zhongxi.guoyuan.view.personalCenter;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.navisdk.adapter.BNCommonSettingParam;
import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNRouteGuideManager;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.bumptech.glide.Glide;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.fragment.beautifulStoreOrder.StoreOrderHasCompleteFragment;
import com.zhongxi.guoyuan.fragment.beautifulStoreOrder.StoreOrderHasDealFragment;
import com.zhongxi.guoyuan.fragment.beautifulStoreOrder.StoreOrderHasNoApplyFragment;
import com.zhongxi.guoyuan.fragment.beautifulStoreOrder.StoreOrderHasNoDealFragment;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.GlideRoundTransform;
import com.zhongxi.guoyuan.view.HtmlActivity;
import com.zhongxi.guoyuan.view.MainActivity;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

public class BeautifulStoreOrderActivity extends BaseActivity implements View.OnClickListener {

    //地图导航
    private static final String APP_FOLDER_NAME = "Meirongyuan";
    public static final String ROUTE_PLAN_NODE = "routePlanNode";
    private String mSDCardPath = null;
    public static List<Activity> activityList = new LinkedList<Activity>();
    private int currentIndex, index;


    private final static String authBaseArr[] =
            {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION};

    private final static int authBaseRequestCode = 1;

    /**
     * 内部TTS播报状态回传handler
     */
    private Handler ttsHandler = new Handler() {
        public void handleMessage(Message msg) {
            int type = msg.what;
            switch (type) {
                case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
                    break;
                }
                case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * 内部TTS播报状态回调接口
     */
    private BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() {
        @Override
        public void playEnd() {
        }

        @Override
        public void playStart() {
        }
    };

    private Button[] tabs;
    private StoreOrderHasNoApplyFragment noPayFragment;
    private StoreOrderHasNoDealFragment noDealFragment;
    private StoreOrderHasDealFragment dealFragment;
    private StoreOrderHasCompleteFragment completeFragment;
    private Fragment[] fragments;
    private TextView tvUserName;
    private TextView tvUserPhone;
    private ImageView ivUserHead;
    private TextView tvBonusPoint;
    private TextView tvIdentify;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_beautiful_store_order);
        initTitle();
        tvTitle.setText("美容预约列表");
        initPageView();

        tvUserName = (TextView) findViewById(R.id.tvUserName);
        tvUserPhone = (TextView) findViewById(R.id.tvUserPhone);
        ivUserHead = (ImageView) findViewById(R.id.ivUserHead);
        tvBonusPoint = (TextView) findViewById(R.id.tvBonusPoint);
        tvIdentify = (TextView) findViewById(R.id.tvIdentify);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.MODIFY_AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS) != PackageManager.PERMISSION_GRANTED) {
            //申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.MODIFY_AUDIO_SETTINGS, Manifest.permission.INTERNET, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS}, 100);
        } else {
            mapNavi();//初始化百度导航
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == authBaseRequestCode) {
            for (int ret : grantResults) {
                if (ret == 0) {
                    continue;
                } else {
//                    Toast.makeText(StoreDetailActivity.this, "缺少导航基本的权限!", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            initNavi();
        } else if (requestCode==100){
            mapNavi();//初始化百度导航
        }
    }

    private void mapNavi() {
        activityList.add(this);
        if (initDirs()) {
            initNavi();
        }
    }

    /**
     * 获取目录
     *
     * @return
     */
    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    private boolean hasBasePhoneAuth() {
        PackageManager pm = getPackageManager();
        for (String auth : authBaseArr) {
            if (pm.checkPermission(auth, getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    String authinfo = null;

    private void initNavi() {

        BNOuterTTSPlayerCallback ttsCallback = null;

        if (android.os.Build.VERSION.SDK_INT >= 23) {

            if (!hasBasePhoneAuth()) {
                requestPermissions(authBaseArr, authBaseRequestCode);
                return;
            }
        }

        BaiduNaviManager.getInstance().init(this, mSDCardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() {
            @Override
            public void onAuthResult(int status, String msg) {
                if (0 == status) {
//                    authinfo = "key校验成功!";
                } else {
//                    authinfo = "key校验失败, " + msg;
                }
                BeautifulStoreOrderActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
//                        Toast.makeText(context, authinfo, Toast.LENGTH_LONG).show();
                    }
                });
            }

            public void initSuccess() {
//                Toast.makeText(context, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
                initSetting();
            }

            public void initStart() {
//                Toast.makeText(context, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
            }

            public void initFailed() {
//                Toast.makeText(context, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
            }


        }, null, ttsHandler, ttsPlayStateListener);

    }

    private void initSetting() {
        // 设置是否双屏显示
        BNaviSettingManager.setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
        // 设置导航播报模式
        BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
        // 是否开启路况
        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);

        Bundle bundle = new Bundle();
        // 必须设置APPID，否则会静音
        bundle.putString(BNCommonSettingParam.TTS_APP_ID, Constants.BAIDUMAP_ID);
        BNaviSettingManager.setNaviSdkParam(bundle);
    }

    private void initPageView() {
        tabs = new Button[4];
        tabs[0] = (Button) findViewById(R.id.tab0);
        tabs[1] = (Button) findViewById(R.id.tab1);
        tabs[2] = (Button) findViewById(R.id.tab2);
        tabs[3] = (Button) findViewById(R.id.tab3);
        noPayFragment = new StoreOrderHasNoApplyFragment();
        noDealFragment = new StoreOrderHasNoDealFragment();
        dealFragment = new StoreOrderHasDealFragment();
        completeFragment = new StoreOrderHasCompleteFragment();
        fragments = new Fragment[]{noPayFragment, noDealFragment, dealFragment, completeFragment};
        tabs[0].setSelected(true);
        getSupportFragmentManager().beginTransaction()
                .add(R.id.relaContainer, noPayFragment).commit();
    }

    @Override
    protected void initData() {
        super.initData();
        initViewData();
    }

    private void initViewData() {
        try {
            Glide.with(context)
                    .load(Url.BASE_URL + MyApplication.getInstance().getAvatar())
                    .placeholder(R.mipmap.logo)
//                    .transform(new GlideRoundTransform(context, 20))
                    .into(ivUserHead);

            if (null != MyApplication.getInstance().getUserName() && !"".equals(MyApplication.getInstance().getUserName())) {
                tvUserName.setText(MyApplication.getInstance().getUserName());
            } else {
                tvUserName.setText(R.string.app_name);
            }
            if (null != MyApplication.getInstance().getPhone() && !"".equals(MyApplication.getInstance().getPhone())) {
                tvUserPhone.setText(MyApplication.getInstance().getPhone());
            } else {
                tvUserPhone.setText(R.string.nophone);
            }
            if (null != MyApplication.getInstance().getInnerCurrency() && !"".equals(MyApplication.getInstance().getInnerCurrency())) {
                tvIdentify.setText(MyApplication.getInstance().getInnerCurrency() + "美豆");
            } else {
                tvIdentify.setText("0 美豆");
            }

            if (TextUtils.isEmpty(MyApplication.getInstance().getHdCurrency())) {
                tvBonusPoint.setText("0红豆");
            } else {
                tvBonusPoint.setText(DataUtil.formatDataSixPoint(MyApplication.getInstance().getHdCurrency()) + "红豆");
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tabs[0].setOnClickListener(this);
        tabs[1].setOnClickListener(this);
        tabs[2].setOnClickListener(this);
        tabs[3].setOnClickListener(this);

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tab0:
                index = 0;
                break;
            case R.id.tab1:
                index = 1;
                break;
            case R.id.tab2:
                index = 2;
                break;
            case R.id.tab3:
                index = 3;
                break;
        }
        if (currentIndex != index) {
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            trx.hide(fragments[currentIndex]);
            if (!fragments[index].isAdded()) {
                trx.add(R.id.relaContainer, fragments[index]);
            }
            trx.show(fragments[index]).commit();
        }
        tabs[currentIndex].setSelected(false);
        tabs[index].setSelected(true);
        currentIndex = index;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        fragments[3].onActivityResult(requestCode, resultCode, data);
    }
}